/*
 * Copyright (c) 2010-2025 Eclipse Dirigible contributors
 *
 * All rights reserved. This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v2.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v20.html
 *
 * SPDX-FileCopyrightText: Eclipse Dirigible contributors SPDX-License-Identifier: EPL-2.0
 */
package org.eclipse.dirigible.parsers.typescript.apidoc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;

public class ApiIndexGenerator {

    /**
     * Generates index.md and index.json based on the markdown API files already generated by the
     * parser.
     *
     * @param rootDir the root directory containing the generated API docs e.g. Paths.get("docs/api")
     * @throws IOException when file operations fail
     */
    public static void generateApiIndexes(Path rootDir) throws IOException {

        List<Path> mdFiles = Files.walk(rootDir)
                                  .filter(p -> p.getFileName()
                                                .toString()
                                                .endsWith(".md"))
                                  .filter(p -> !p.getFileName()
                                                 .toString()
                                                 .equals("index.md"))
                                  .collect(Collectors.toList());

        // Group by directory name (module name)
        Map<String, List<Path>> grouped = mdFiles.stream()
                                                 .collect(Collectors.groupingBy(path -> {
                                                     Path parent = path.getParent();
                                                     return parent != null ? parent.getFileName()
                                                                                   .toString()
                                                             : "misc";
                                                 }));

        // Generate index.md
        StringBuilder indexMd = new StringBuilder("# API Documentation\n\n");
        grouped.keySet()
               .stream()
               .sorted()
               .forEach(group -> {
                   indexMd.append("## ")
                          .append(group.toUpperCase())
                          .append("\n\n");
                   grouped.get(group)
                          .stream()
                          .sorted()
                          .forEach(p -> {
                              String name = p.getFileName()
                                             .toString()
                                             .replace(".md", "");
                              indexMd.append("- [")
                                     .append(name)
                                     .append("](")
                                     .append("./")
                                     .append(group)
                                     .append("/")
                                     .append(name)
                                     .append(".md")
                                     .append(")\n");
                          });
                   indexMd.append("\n");
               });

        Files.writeString(rootDir.resolve("index.md"), indexMd.toString());

        // Generate index.json matching VitePress sidebar format
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode rootArray = mapper.createArrayNode();

        grouped.keySet()
               .stream()
               .sorted()
               .forEach(group -> {
                   ObjectNode groupNode = mapper.createObjectNode();
                   groupNode.put("text", group.toUpperCase());
                   groupNode.put("link", "/documentation/platform/api/" + group + "/");
                   groupNode.put("collapsed", true);

                   ArrayNode itemsArray = mapper.createArrayNode();
                   grouped.get(group)
                          .stream()
                          .sorted()
                          .forEach(p -> {
                              String name = p.getFileName()
                                             .toString()
                                             .replace(".md", "");
                              ObjectNode itemNode = mapper.createObjectNode();
                              itemNode.put("text", capitalize(name));
                              itemNode.put("link", "/documentation/platform/api/" + group + "/" + name);
                              itemsArray.add(itemNode);
                          });

                   groupNode.set("items", itemsArray);
                   rootArray.add(groupNode);
               });

        mapper.writerWithDefaultPrettyPrinter()
              .writeValue(rootDir.resolve("index.json")
                                 .toFile(),
                      rootArray);
    }

    private static String capitalize(String value) {
        if (value == null || value.isEmpty())
            return value;
        return value.substring(0, 1)
                    .toUpperCase()
                + value.substring(1);
    }
}

